import logging
from django.contrib.auth import get_user_model
from django.utils import timezone
from rest_framework_simplejwt.tokens import RefreshToken
from .models import BlacklistedToken

User = get_user_model()
logger = logging.getLogger(__name__)


def refresh_user_token(user):
    """
    为用户刷新JWT令牌并更新到数据库
    
    Args:
        user: User对象
        
    Returns:
        dict: 包含新令牌的字典
    """
    try:
        # 检查用户是否有刷新令牌
        if not user.refresh_token:
            raise ValueError("用户没有刷新令牌")
            
        # 检查刷新令牌是否在黑名单中
        if BlacklistedToken.objects.filter(token=user.refresh_token, expires_at__gt=timezone.now()).exists():
            raise ValueError("刷新令牌已在黑名单中")
            
        # 创建刷新令牌对象
        refresh_token = RefreshToken(user.refresh_token)
        
        # 生成新的访问令牌
        new_access_token = str(refresh_token.access_token)
        
        # 检查是否需要轮换刷新令牌
        new_refresh_token = None
        if hasattr(refresh_token, 'rotate'):
            # 如果启用了令牌轮换
            new_refresh_token = str(refresh_token.rotate())
        else:
            # 否则使用原有的刷新令牌
            new_refresh_token = user.refresh_token
            
        # 更新用户表中的令牌
        user.access_token = new_access_token
        user.refresh_token = new_refresh_token
        user.save(update_fields=['access_token', 'refresh_token'])
        
        return {
            'access': new_access_token,
            'refresh': new_refresh_token
        }
        
    except Exception as e:
        logger.exception(f"刷新用户 {user.id} 的令牌失败: {str(e)}")
        raise